<template>
  <div class="shop-page">
    <div class="shop-header">
      <h2>智教商城</h2>
      <p>精选优质课程和学习资源</p>
      <!-- 添加购物车图标和数量显示 -->
      <div class="cart-icon-container" @click="showCartModal">
        <ShoppingCartOutlined class="header-cart-icon" />
        <span v-if="cartCount > 0" class="cart-count">{{ cartCount  }}</span>
      </div>
    </div>

  <!-- 购物车详情弹窗 -->
<div v-if="showCart" class="cart-modal" @click.self="showCart = false">
  <div class="cart-content">
    <div class="cart-header">
      <h3>我的购物车</h3>
      <CloseOutlined class="close-icon" @click="showCart = false" />
    </div>
    
    <div v-if="cartLoading" class="cart-loading">
      <a-spin />
    </div>
    
    <div v-else-if="cartItemGroups.length === 0" class="empty-cart">
      购物车为空
    </div>
    
    <div v-else class="cart-items-grouped">
      <div 
        v-for="group in cartItemGroups" 
        :key="group.sellerId" 
        class="seller-group"
      >
        <div class="seller-header">
          <a-checkbox
            :checked="isSellerAllSelected(group.sellerId)"
            @change="toggleSellerSelectAll(group.sellerId, $event.target.checked)"
          />
          <span class="seller-name">商家: {{ group.sellerName }}</span>
        </div>
        <!-- 在购物车商品项中添加删除按钮 -->
        <div 
          v-for="item in group.items" 
          :key="item.id" 
          class="cart-item"
        >
          <a-checkbox
            :checked="selectedCartItemIds.includes(item.id)"
            @change="toggleItemSelect(item.id, $event.target.checked)"
            class="item-checkbox"
          />
          <img :src="item.cover" :alt="item.title" class="item-image" />
          <div class="item-details">
            <h4>{{ item.title }}</h4>
            <p>¥{{ item.price }}</p>
          </div>
          <div class="item-quantity">
            <button @click="updateQuantity(item.id, item.quantity - 1)">-</button>
            <span>{{ item.quantity }}</span>
            <button @click="updateQuantity(item.id, item.quantity + 1)">+</button>
          </div>
            <!-- 添加删除按钮 -->
    <button @click="removeFromCart(item.id)" class="remove-item-btn">删除</button>
        </div>
      </div>
      
      <div class="cart-footer">
        <div class="select-all">
          <a-checkbox
            :checked="isAllSelected"
            @change="toggleSelectAll($event.target.checked)"
          >
            全选
          </a-checkbox>
        </div>
        <div class="total">总计: ¥{{ selectedTotalAmount.toFixed(2) }}</div>
        <a-button type="primary" @click="checkoutSelected()">去结算</a-button>
      </div>
    </div>
  </div>
</div>
    
    <!-- 商城分类 - 使用下拉框形式展示一级和二级分类 -->
    <div class="shop-categories">
      <div class="category-item all-category" 
           :class="{ active: activeCategory === 0 }"
           @click="selectCategory(0)">
        全部商品
      </div>
      
      <Dropdown 
        v-for="topCategory in topCategories" 
        :key="topCategory.id"
        placement="bottom"
      >
        <template #overlay>
          <Menu @click="handleMenuClick">
            <MenuItemGroup :title="topCategory.name">
              <MenuItem 
                v-for="level1 in getChildrenByParentId(topCategory.id)" 
                :key="level1.id"
                :data-id="level1.id"
              >
                {{ level1.name }}
              </MenuItem>
            </MenuItemGroup>
          </Menu>
        </template>
        <div class="category-item dropdown-category" 
             :class="{ active: isCategoryActive(topCategory.id) }">
          {{ topCategory.name }}
          <DownOutlined />
        </div>
      </Dropdown>
    </div>
    
    <!-- 商品网格 -->
    <div class="shop-grid">
      <div v-for="product in filteredProducts" :key="product.productId" class="product-card" @click="viewProduct(product)">
        <div class="product-image">
          <img :src="product.mainImage" :alt="product.productName" />
          <!-- <div class="product-overlay">
            <ShoppingCartOutlined class="cart-icon" @click.stop="addToCart(product)" />
          </div> -->
        </div>
        <div class="product-info">
          <h3 class="product-name">{{ product.productName }}</h3>
          <p class="product-desc">{{ product.description }}</p>
          <div class="product-meta">
            <div class="product-price">
              <span class="current-price">¥{{ product.price }}</span>
            </div>
            <!-- <button @click.stop="handleBuy(product)">购买</button> -->
            <div class="product-stats">
              <span class="sales">已售 {{ formatSales(product?.sales)  }}</span>
              <span class="rating">⭐ {{ product.rating }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed ,watch } from 'vue'
import { message } from 'ant-design-vue'
import { ShoppingCartOutlined, CloseOutlined, DownOutlined } from '@ant-design/icons-vue'
import { Dropdown, Menu, MenuItemGroup, MenuItem } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { createOrder1 } from '@/api/mall/alipayController'

import { addOrder } from '@/api/mall/bizOrderController'
import { addDetails } from '@/api/mall/bizOrderDetailController'
import { useAuthStore } from '@/stores/authStore'
// 导入购物车状态管理
import { useCartStore } from '@/stores/cartStore'
import { storeToRefs } from 'pinia'
import { decreaseStocks } from '@/api/mall/bizProductController'
import { listCartItemGroupBySeller } from '@/api/cart/bizCartItemController'
const authStore = useAuthStore()

const router = useRouter()
// 使用购物车状态管理
const cartStore = useCartStore()
// 使用 storeToRefs 保持响应性
const { cartItems, cartCount, cartTotal } = storeToRefs(cartStore)
// 当前选择的商品
const currentProduct = ref<Product | null>(null)
// 购买数量
const quantity = ref(1)
// 是否显示购买弹窗
const showBuyDialog = ref(false)

// 修改购物车相关状态
const showCart = ref(false)
const cartLoading = ref(false)

// 定义购物车商品分组数据结构
interface CartItemGroup {
  sellerId: number
  sellerName: string
  items: CartItem[]
}

// 购物车商品分组数据
const cartItemGroups = ref<CartItemGroup[]>([])

// 选中的商品ID列表
const selectedCartItemIds = ref<number[]>([])


// 添加从购物车移除商品的方法
const removeFromCart = async (productId: number) => {
  try {
    // 从前端界面中移除商品
    cartItemGroups.value = cartItemGroups.value.map(group => ({
      ...group,
      items: group.items.filter(item => item.id !== productId)
    })).filter(group => group.items.length > 0); // 移除空的商家组
    
    // 从选中列表中移除
    selectedCartItemIds.value = selectedCartItemIds.value.filter(id => id !== productId);
    
    // 保存到 localStorage
    const userId = authStore.userInfo.id;
    const localCartKey = `localCartUpdates_${userId}`;
    const localUpdates = JSON.parse(localStorage.getItem(localCartKey) || '{}');
    
    // 标记为已删除（使用负数或特殊值表示删除）
    localUpdates[productId] = 0; // 0表示删除
    localStorage.setItem(localCartKey, JSON.stringify(localUpdates));
    
    message.success('商品已从购物车移除');
  } catch (error) {
    message.error('移除商品失败');
    console.error('移除商品失败:', error);
  }
};

// 获取购物车数据
const fetchCartItems = async () => {
    console.log('开始获取购物车数据...')
  console.log('用户信息:', authStore.userInfo)

  if (!authStore.userInfo?.id) {
    message.warning('请先登录')
    return
  }
  
  cartLoading.value = true
  try {
    const res = await listCartItemGroupBySeller({
      userId: authStore.userInfo.id
    })
    console.log(res.data);
    
    console.log('获取购物车数据:', res);
    

const convertToProductsArr = (cartData) => {
  const productsArr = {
    products: []
  };
  
  // 遍历每个商家的购物车项
  cartData.forEach(sellerGroup => {
    // 遍历该商家的每个商品
    sellerGroup.cartItemList.forEach(item => {
      productsArr.products.push({
        productId: item.productId,
        quantity: item.quantity,
        productName:item.productName,
        price:item.price
      });
    });
  });
  
  return productsArr;
};

// 使用转换函数
const productsArrData = convertToProductsArr(res.data);
console.log('转换后的数据:', productsArrData);




    
     // 处理返回的数据
    if (res.code === "00000" && res.data && res.data.length > 0) {
      // 提取 cartItemList 数据
      const cartItemList = res.data[0].cartItemList || []

          // 获取本地存储的修改记录
      const userId = authStore.userInfo.id
      const localCartKey = `localCartUpdates_${userId}`
      const localUpdates = JSON.parse(localStorage.getItem(localCartKey) || '{}')
      
       // 处理购物车项目，包括数量更新和删除过滤
      const processedCartItems = cartItemList.map(item => {
        const localQuantity = localUpdates[item.productId];
        
        // 如果标记为删除(0)则过滤掉该商品
        if (localQuantity === 0) {
          return null;
        }
        
        // 使用本地数量或原始数量
        const quantity = (localQuantity !== undefined && localQuantity > 0) 
          ? localQuantity 
          : Number(item.quantity) || 1;
        
        return {
          ...item,
          quantity: quantity
        };
      }).filter(item => item !== null); // 过滤掉被标记删除的商品
      
      // 按 sellerUserId 分组
      const groupedItems: Record<number, CartItem[]> = {}
      
      processedCartItems.forEach(item => {
        const sellerId = item.sellerUserId || 0
        if (!groupedItems[sellerId]) {
          groupedItems[sellerId] = []
        }



        groupedItems[sellerId].push({
          id: item.productId,
          productId: item.productId,
          sellerUserId: item.sellerUserId,
          title: item.productName,
          productName: item.productName,
          price: Number(item.price) || 0,  // 确保价格是数字类型
          quantity: item.quantity, 
          cover: item.mainImage,
          mainImage: item.mainImage,
          description: item.description || ''
        })
      })
      
      // 转换为数组格式
      cartItemGroups.value = Object.entries(groupedItems).map(([sellerId, items]) => ({
        sellerId: parseInt(sellerId),
        sellerName: `商家${sellerId}`, // 可以从后端获取真实商家名称
        items: items
      }))


      
 
      
   // 默认选中所有商品
      const allItemIds = cartItemGroups.value.flatMap(group => 
        group.items.map(item => item.id)
      )
      selectedCartItemIds.value = allItemIds
    } else {
      message.error(res.message || '获取购物车数据失败')
         // 即使没有服务器数据，也要清空界面
      cartItemGroups.value = []
      selectedCartItemIds.value = []
    }
  } catch (error) {
    message.error('获取购物车数据失败')
    console.error('获取购物车数据失败:', error)
     // 出错时也要清空界面
    cartItemGroups.value = []
    selectedCartItemIds.value = []
  } finally {
    cartLoading.value = false
  }
}
// 显示购物车时获取数据
const showCartModal = () => {
  showCart.value = true
  console.log('显示购物车弹窗');
  
  fetchCartItems()
}

// 检查商家是否全选
const isSellerAllSelected = (sellerId: number) => {
  const group = cartItemGroups.value.find(g => g.sellerId === sellerId)
  if (!group || group.items.length === 0) return false
  
  return group.items.every(item => selectedCartItemIds.value.includes(item.id))
}

// 切换商家全选状态
const toggleSellerSelectAll = (sellerId: number, checked: boolean) => {
  const group = cartItemGroups.value.find(g => g.sellerId === sellerId)
  if (!group) return
  
  if (checked) {
    // 添加该商家所有商品到选中列表
    const newItemIds = group.items
      .map(item => item.id)
      .filter(id => !selectedCartItemIds.value.includes(id))
    selectedCartItemIds.value = [...selectedCartItemIds.value, ...newItemIds]
  } else {
    // 从选中列表中移除该商家所有商品
    const itemIdsToRemove = group.items.map(item => item.id)
    selectedCartItemIds.value = selectedCartItemIds.value.filter(
      id => !itemIdsToRemove.includes(id)
    )
  }
}

// 切换单个商品选中状态
const toggleItemSelect = (itemId: number, checked: boolean) => {
  if (checked) {
    if (!selectedCartItemIds.value.includes(itemId)) {
      selectedCartItemIds.value = [...selectedCartItemIds.value, itemId]
    }
  } else {
    selectedCartItemIds.value = selectedCartItemIds.value.filter(id => id !== itemId)
  }
}

// 检查是否全选
const isAllSelected = computed(() => {
  const allItemIds = cartItemGroups.value.flatMap(group => 
    group.items.map(item => item.id)
  )
  return allItemIds.length > 0 && 
         allItemIds.every(id => selectedCartItemIds.value.includes(id))
})

// 全选/取消全选
const toggleSelectAll = (checked: boolean) => {
  if (checked) {
    const allItemIds = cartItemGroups.value.flatMap(group => 
      group.items.map(item => item.id)
    )
    selectedCartItemIds.value = allItemIds
  } else {
    selectedCartItemIds.value = []
  }
}

// 计算选中商品总价
const selectedTotalAmount = computed(() => {
  return cartItemGroups.value.reduce((total, group) => {
    const groupTotal = group.items.reduce((groupSum, item) => {
      if (selectedCartItemIds.value.includes(item.id)) {
        return groupSum + (item.price * item.quantity)
      }
      return groupSum
    }, 0)
    return total + groupTotal
  }, 0)
})

// 更新商品数量
const updateQuantity = async (productId: number, newQuantity: number) => {
  // 验证数量
  if (newQuantity <= 0) {
    message.info('数量不能小于1')
    return
  }

   try {
    // 更新前端显示
    cartItemGroups.value.forEach(group => {
      const item = group.items.find(i => i.id === productId)
      if (item) {
        item.quantity = newQuantity
      }
    })

       // 保存到 localStorage
    const userId = authStore.userInfo.id
    const localCartKey = `localCartUpdates_${userId}`
    const localUpdates = JSON.parse(localStorage.getItem(localCartKey) || '{}')
    localUpdates[productId] = newQuantity
    localStorage.setItem(localCartKey, JSON.stringify(localUpdates))
    
    message.success('数量更新成功')
  } catch (error) {
    message.error('数量更新失败')
    console.error('更新商品数量失败:', error)
  }
}
  
  


// 3. 在结算时清除本地存储的修改记录
const checkoutSelected = async () => {
  // 修改变量名，避免重复
  const selectedCartItems = cartItemGroups.value.flatMap(group => 
    group.items.filter(item => selectedCartItemIds.value.includes(item.id))
  )
  
  if (selectedCartItems.length === 0) {
    message.warning('请至少选择一个商品')
    return
  }
  
  try {
    // 1. 批量扣减库存
    // const stockDecreaseRequests = selectedCartItems.map(item => ({
    //   productId: item.productId,
    //   quantity: item.quantity
    // }))
    
    // const stockDecreaseRes = await decreaseStocks(stockDecreaseRequests)
    
    // if (!stockDecreaseRes || stockDecreaseRes.code !== '00000') {
    //   message.error(stockDecreaseRes?.message || '库存扣减失败')
    //   return
    // }
    
    // 2. 生成订单号
    const orderNo = generateOrderNo()
    
    // 3. 计算总金额
    const totalAmount = selectedCartItems.reduce((sum, item) => 
      sum + (item.price * item.quantity), 0
    )
      const stockDecreaseRequests = selectedCartItems.map(item => ({
      productId: item.productId,
      quantity: item.quantity
    }))
    
    // 4. 创建订单主表记录
    const orderData = {
      orderNo,
      userId: authStore.userInfo.id,
      totalAmount,
      payAmount: totalAmount,
      orderStatus: 0, // 0-待支付
      paymentId: 1, // 假设支付方式ID为1
      paymentMethod: 'alipay',
       // 假设支付方式为支付宝
    }
    
      const orderRes = await addOrder({
      order: orderData,
      stockDecreaseRequests: stockDecreaseRequests
    })
    
    if (!orderRes) throw new Error('创建订单失败')
    
    // 5. 创建订单详情记录（批量添加）
    const orderDetailData = selectedCartItems.map(item => ({
      orderNo,
      productId: item.productId,
      productName: item.productName,
      productImage: item.mainImage,
      productPrice: item.price,
      quantity: item.quantity,
      totalPrice: item.price * item.quantity,
      sellerUserId: item.sellerUserId
    }))
    
    const detailRes = await addDetails(orderDetailData)
    if (!detailRes) throw new Error('创建订单详情失败')
    
    // 6. 存储订单信息到sessionStorage
    const orderInfo = {
      orderNo,
      products: selectedCartItems.map(item => ({
        productId: item.productId,
        productName: item.productName,
        price: item.price,
        quantity: item.quantity,
        mainImage: item.mainImage
      })),
      totalAmount,
      createdAt: new Date().getTime()
    }
    
    sessionStorage.setItem('currentOrder', JSON.stringify(orderInfo))
    
    // 7. 清除本地存储的购物车修改记录
    const userId = authStore.userInfo.id
    const localCartKey = `localCartUpdates_${userId}`
    localStorage.removeItem(localCartKey)
    
    // 8. 跳转到收银台
    router.push({
      path: '/cashier',
      query: { orderNo }
    })
    
    showCart.value = false
    message.success('订单创建成功，请完成支付')
    
  } catch (error) {
    message.error('结算失败，请重试')
    console.error('结算失败:', error)
  }
}


// 打开购买弹窗
const handleBuy = (product: Product) => {
  currentProduct.value = product
  quantity.value = 1
  showBuyDialog.value = true
}

// 关闭购买弹窗
const closeBuyDialog = () => {
  showBuyDialog.value = false
}

// 添加商家分组的计算属性
const groupedCartItems = computed(() => {
  const grouped: Record<number, CartItem[]> = {}
  cartItems.value.forEach(item => {
    const sellerId = item.sellerUserId || 0 // 如果没有sellerUserId，默认为0
    if (!grouped[sellerId]) {
      grouped[sellerId] = []
    }
    grouped[sellerId].push(item)
  })
  return grouped
})

// 添加选中商品的状态
const selectedItems = ref<Record<number, boolean>>({})

// 初始化选中状态
watch(cartItems, (newItems) => {
  newItems.forEach(item => {
    if (!(item.id in selectedItems.value)) {
      selectedItems.value[item.id] = true // 默认选中所有商品
    }
  })
}, { immediate: true })

// // 全选功能
// const toggleSelectAll = (sellerId: number, checked: boolean) => {
//   const items = groupedCartItems.value[sellerId] || []
//   items.forEach(item => {
//     selectedItems.value[item.id] = checked
//   })
// }

// // 检查是否全选
// const isSellerAllSelected = (sellerId: number) => {
//   const items = groupedCartItems.value[sellerId] || []
//   return items.length > 0 && items.every(item => selectedItems.value[item.id])
// }

// // 计算选中商品的总价
// const selectedTotalAmount = computed(() => {
//   return cartItems.value.reduce((total, item) => {
//     if (selectedItems.value[item.id]) {
//       return total + (item.price * item.quantity)
//     }
//     return total
//   }, 0)
// })

// 结算选中的商品
// const checkoutSelected = () => {
//   const selected = cartItems.value.filter(item => selectedItems.value[item.id])
//   if (selected.length === 0) {
//     message.warning('请至少选择一个商品')
//     return
//   }
  
//   message.success(`已选择 ${selected.length} 个商品，开始结算`)
//   showCart.value = false
//   // 这里可以添加实际的结算逻辑
// }

// 确认购买
// const confirmBuy = () => {
//   if (!currentProduct.value) return
  
//   message.success(`成功购买 ${currentProduct.value.productName} ${quantity.value}件，总价 ¥${(currentProduct.value.price * quantity.value).toFixed(2)}`)
//   closeBuyDialog()
//    router.push({
//     path: '/cashier',
//     query: {
//       product: encodeURIComponent(JSON.stringify({
//         productId: currentProduct.value.productId,
//         productName: currentProduct.value.productName,
//         price: currentProduct.value.price,
//         mainImage: currentProduct.value.mainImage
//       })),
//       quantity: quantity.value.toString()
//     }
//   })
  
//   closeBuyDialog()
//   // 这里可以调用实际的购买接口
//   // await createOrder(...)

  
// }
// const confirmBuy = () => {
//   if (!currentProduct.value) return
  
//   // 生成订单号后存储到sessionStorage
//   const orderNo = generateOrderNo()
//   sessionStorage.setItem('currentOrder', JSON.stringify({
//     orderNo,
//     product: {
//       productId: currentProduct.value.productId,
//       productName: currentProduct.value.productName,
//       price: currentProduct.value.price,
//       mainImage: currentProduct.value.mainImage
//     },
//     quantity: quantity.value,
//     createdAt: new Date().getTime() // 添加时间戳用于验证
//   }))
  
//   router.push({
//     path: '/cashier',
//     query: { orderNo } // 只传订单号
//   })
  
//   closeBuyDialog()
// }
// const confirmBuy = async () => {
//   if (!currentProduct.value || !authStore.userInfo.id) return
//   console.log(currentProduct.value.sellerUserId );
  
//   try {
//     // 1. 创建订单主表记录
//     const orderNo = generateOrderNo()
//     const orderData = {
//       orderNo,
//       userId: authStore.userInfo.id,
//       totalAmount: currentProduct.value.price * quantity.value,
//       payAmount: currentProduct.value.price * quantity.value,
//       orderStatus: 0, // 0-待支付
//       paymentId: 1, // 假设支付方式ID为1
//       paymentMethod: 'alipay' // 假设支付方式为支付宝
//     }
    
//     // 调用添加订单API
//     const orderRes = await addOrder(orderData)
//     if (!orderRes) throw new Error('创建订单失败')
    
//     // 2. 创建订单详情记录
//     const orderDetailData = [{
//       orderNo,
//       productId: currentProduct.value.productId,
//       productName: currentProduct.value.productName,
//       productImage: currentProduct.value.mainImage,
//       productPrice: currentProduct.value.price,
//       quantity: quantity.value,
//       totalPrice: currentProduct.value.price * quantity.value,
//       sellerUserId: currentProduct.value.sellerUserId 
//     }]
    
//     // 调用添加订单详情API
//     const detailRes = await addDetails(orderDetailData)
//     if (!detailRes) throw new Error('创建订单详情失败')
    
//     // 3. 存储订单信息到sessionStorage并跳转到收银台
//     sessionStorage.setItem('currentOrder', JSON.stringify({
//       orderNo,
//       product: {
//         productId: currentProduct.value.productId,
//         productName: currentProduct.value.productName,
//         price: currentProduct.value.price,
//         mainImage: currentProduct.value.mainImage
//       },
//       quantity: quantity.value,
//       createdAt: new Date().getTime()
//     }))
    
//     router.push({
//       path: '/cashier',
//       query: { orderNo }
//     })
    
//     closeBuyDialog()
//   } catch (error) {
//     message.error(`订单创建失败: ${error instanceof Error ? error.message : '未知错误'}`)
//     console.error('订单创建失败:', error)
//   }
// }

//生成订单号
const generateOrderNo = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const random = Math.random().toString(36).substring(2, 10).toUpperCase()
  return `${year}${month}${day}${random}`
}


// 加入购物车并关闭弹窗
const addToCart = (product: Product) => {

    // 保存到 localStorage
  const userId = authStore.userInfo.id;
  if (userId) {
    const localCartKey = `localCartUpdates_${userId}`;
    const localUpdates = JSON.parse(localStorage.getItem(localCartKey) || '{}');
    
     // 处理商品重新添加的情况
    if (localUpdates[product.productId] === 0) {
      // 如果之前被标记为删除，则重置为1
      localUpdates[product.productId] = 1;
    } else if (localUpdates[product.productId]) {
      // 如果已存在则增加数量
      localUpdates[product.productId] += 1;
    } else {
      // 如果不存在则设置为1
      localUpdates[product.productId] = 1;
    }
    
    localStorage.setItem(localCartKey, JSON.stringify(localUpdates));
  }
  cartStore.addToCart({
    id: product.productId,
    title: product.productName,
    cover: product.mainImage,
    price: product.price,
    description: product.description || '',
    quantity: 1
  })
  message.success(`已添加到购物车: ${product.productName}`)
}
// 购买商品
// 购买商品




// 定义返回的商品数据类型
interface Product {
  productId: number;
  sellerUserId: number;
  productName: string;
  price: number;
  status: number;
  mainImage: string;
  createTime: string;
  updateTime: string;
  createBy: string;
  updateBy: string;
  deleted: number;
  stock: number;
  detailImage?: string;
  categoryId: number;
  description?: string;
  sales: number;       // 若后端无sales，设默认值0
  rating: number;
}

// 定义返回的商品分类数据类型
interface Category {
  id: number;
  parentId: number;
  name: string;
}

interface CartItem extends Product {
  quantity: number
}

interface Props {
  products?: Product[]
  categories?: Category[]
}

const props = withDefaults(defineProps<Props>(), {
  products: () => [],
  categories: () => []
})

// Emits
const emit = defineEmits<{
  categoryChange: [categoryId: number]
  productView: [product: Product]
}>()


// const cartItems = ref<CartItem[]>([])

// 计算购物车总价
// const totalAmount = computed(() => {
//   return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0)
// })
const totalAmount = computed(() => cartTotal.value)

// 当前选中的分类
const activeCategory = ref(0) // 默认显示全部商品

// 获取顶级分类（parentId为0）
const topCategories = computed(() => {
  return props.categories.filter(category => category.parentId === 0)
})

// 根据父ID获取子分类
const getChildrenByParentId = (id: number) => {
  // console.log('categories:' ,props.categories);
  return props.categories.filter(category => category.parentId === id)
}

// 检查分类或其子分类是否被选中
const isCategoryActive = (categoryId: number) => {
  if (activeCategory.value === categoryId) return true;
  
  // 检查是否有子分类被选中
  const hasActiveChild = (id: number): boolean => {
    const children = getChildrenByParentId(id)
    if (children.some(child => child.id === activeCategory.value)) {
      return true
    }
    // 递归检查二级子分类
    return children.some(child => hasActiveChild(child.id))
  }
  
  return hasActiveChild(categoryId)
}

// 计算属性：根据分类筛选商品
const filteredProducts = computed(() => {
  if (activeCategory.value === 0) {
    return props.products
  }
  
  // 找出所有需要包含的分类ID（选中的分类及其所有子分类）
  const getAllCategoryIds = (categoryId: number): number[] => {
    const result = [categoryId]
    const children = getChildrenByParentId(categoryId)
    children.forEach(child => {
      result.push(...getAllCategoryIds(child.id))
    })
    return result
  }
  
  const categoryIds = getAllCategoryIds(activeCategory.value)
  
  return props.products.filter(product => 
    categoryIds.includes(product.categoryId)
  )
})

// 方法
const selectCategory = (categoryId: number) => {
  activeCategory.value = categoryId
  emit('categoryChange', categoryId)
}

const viewProduct = (product: Product) => {
  console.log ("传递商品ID:",product.productId)
  if (!product.productId) {  
  message.error('商品ID为空,无法跳转')  
  return  
  }  
   router.push({ 
    name: 'detailShop', 
    params: { goodsId: product.productId } // 传递商品ID
  })
}

// 处理下拉菜单点击
const handleMenuClick = (e: any) => {
  const categoryId = parseInt(e.key)
  if (!isNaN(categoryId)) {
    selectCategory(categoryId)
  }
}


//结算的方法
const checkout = () => {
  message.success('已开始结算')
  showCart.value = false
}

// 更新商品数量
// const updateQuantity = (productId: number, quantity: number) => {
//   if (quantity <= 0) {
//     cartItems.value = cartItems.value.filter(item => item.productId !== productId)
//     return
//   }
  
//   const item = cartItems.value.find(item => item.productId === productId)
//   if (item) {
//     item.quantity = quantity
//   }
// }
// const updateQuantity = (productId: number, quantity: number) => {
//   cartStore.updateQuantity(productId, quantity)
// }

// 格式化销售数量
const formatSales = (sales: number | undefined) => {
  if (!sales || sales === 0) return '0'
  if (sales >= 10000) {
    return (sales / 10000).toFixed(1) + '万'
  } else if (sales >= 1000) {
    return (sales / 1000).toFixed(1) + '千'
  }
  return sales.toString()
}
</script>


<style scoped>
.shop-page {
  padding: 24px;
  position: relative;
}

.shop-header {
  text-align: center;
  margin-bottom: 32px;
  position: relative;
}

.shop-header h2 {
  font-size: 32px;
  color: #fff;
  margin-bottom: 8px;
}

.shop-header p {
  font-size: 16px;
  color: #999;
}

/* 购物车图标样式 */
.cart-icon-container {
  position: absolute;
  top: 0;
  right: 0;
  font-size: 24px;
  color: #fff;
  cursor: pointer;
  padding: 10px;
  z-index: 100;
}

.header-cart-icon {
  transition: transform 0.3s;
}

.cart-icon-container:hover .header-cart-icon {
  transform: scale(1.1);
}

.cart-count {
  position: absolute;
  top: 0;
  right: 0;
  background-color: #ff4757;
  color: white;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

/* 购物车弹窗样式 */
.cart-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  justify-content: flex-end;
}

.cart-content {
  background: #0f3460;
  width: 400px;
  height: 100%;
  padding: 20px;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  color: #fff;
}

.close-icon {
  cursor: pointer;
  font-size: 20px;
}

.empty-cart {
  text-align: center;
  color: #999;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cart-items {
  flex: 1;
  overflow-y: auto;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  color: #fff;
}

.item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  margin-right: 15px;
  border-radius: 8px;
}

.item-details {
  flex: 1;
}

.item-details h4 {
  margin: 0 0 5px 0;
  font-size: 16px;
}

.item-details p {
  margin: 0;
  color: #ff4757;
  font-weight: bold;
}

.item-quantity {
  display: flex;
  align-items: center;
  gap: 10px;
}

.item-quantity button {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  border: none;
  cursor: pointer;
}

.item-quantity span {
  min-width: 20px;
  text-align: center;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.total {
  color: #fff;
  font-size: 18px;
  font-weight: bold;
}

/* 分类样式修改 */
.shop-categories {
  display: flex;
  gap: 16px;
  margin-bottom: 32px;
  overflow-x: auto;
  padding-bottom: 8px;
  flex-wrap: wrap;
}

.category-item {
  padding: 8px 20px;
  border-radius: 20px;
  background: rgba(255, 255, 255, 0.1);
  color: #ddd;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
  border: 1px solid rgba(255, 255, 255, 0.2);
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.dropdown-category {
  padding-right: 28px;
}

.category-item:hover {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
}

.category-item.active {
  background: #ff4757;
  color: #fff;
  border-color: #ff4757;
}

/* 商品网格样式保持不变 */
.shop-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
}

.product-card {
  background: rgba(15, 52, 96, 0.8);
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
  border-color: rgba(255, 255, 255, 0.2);
}

.product-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.product-card:hover .product-image img {
  transform: scale(1.05);
}

.product-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.product-card:hover .product-overlay {
  opacity: 1;
}

.cart-icon {
  font-size: 32px;
  color: #fff;
}

.product-info {
  padding: 16px;
}

.product-name {
  font-size: 18px;
  font-weight: 600;
  color: #fff;
  margin-bottom: 8px;
}

.product-desc {
  font-size: 14px;
  color: #999;
  margin-bottom: 12px;
  line-height: 1.4;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 8px;
}

.current-price {
  font-size: 20px;
  font-weight: 600;
  color: #ff4757;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.product-stats {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #999;
}

.cart-items-grouped {
  flex: 1;
  overflow-y: auto;
}

.seller-group {
  margin-bottom: 20px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 15px;
}

.seller-header {
  display: flex;
  align-items: center;
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  margin-bottom: 10px;
}

.seller-name {
  margin-left: 10px;
  font-weight: bold;
  color: #fff;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  color: #fff;
}

.item-checkbox {
  margin-right: 15px;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.select-all {
  color: #fff;
}

.select-all :deep(.ant-checkbox-wrapper) {
  color: #fff;
}
.cart-loading {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

/* 添加删除按钮样式 */
.remove-item-btn {
  margin-left: 10px;
  padding: 5px 10px;
  background-color: #ff4757;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.remove-item-btn:hover {
  background-color: #ff2e43;
}

/* 下拉菜单样式 */
:deep(.ant-dropdown-menu) {
  background-color: #0f3460;
  border-color: rgba(255, 255, 255, 0.1);
}

:deep(.ant-dropdown-menu-item) {
  color: #ddd;
}

:deep(.ant-dropdown-menu-item:hover) {
  background-color: rgba(255, 255, 255, 0.1);
  color: #fff;
}

:deep(.ant-dropdown-menu-group-title) {
  color: #fff;
  font-weight: 600;
}
</style>